﻿using System.Collections.Generic;
using System.Linq;
using BlizzardApi;
using Model;
using Achievement = BlizzardApi.Model.Achievement;
using AchievementCategory = BlizzardApi.Model.AchievementCategory;

namespace Command.Commands
{
    public class SyncGuildAchievementsCommand : BaseCommand<Options>
    {
        private readonly IWowService _wowService;
        private readonly IRepository _repository;

        public SyncGuildAchievementsCommand(IWowService wowService, IRepository repository)
        {
            _wowService = wowService;
            _repository = repository;
        }

        protected override void InternalExecute(Options options)
        {
            var categories = _wowService.GetGuildAchievementCategories();
            ProcessCategories(categories);
        }

        private void ProcessCategories(IEnumerable<AchievementCategory> categories)
        {
            foreach (var category in categories)
            {
                if (category.Categories != null)
                    ProcessCategories(category.Categories);
                if (category.Achievements != null)
                    ProcessAchievements(category.Achievements);
            }
        }

        private void ProcessAchievements(IEnumerable<Achievement> achievements)
        {
            foreach (var achievement in achievements)
                ProcessAchievement(achievement);
        }

        private void ProcessAchievement(Achievement achievement)
        {
            var modelAchievement = _repository.Query<Model.Achievement>().FirstOrDefault(x => x.ExternalKey == achievement.ID);
            if (modelAchievement == null)
            {
                modelAchievement = new Model.Achievement
                                       {
                                           ExternalKey = achievement.ID,
                                           Faction = Faction.Neutral,
                                           Title = achievement.Title,
                                           Description = achievement.Description,
                                           Points = achievement.Points,
                                       };
                _repository.Save(modelAchievement);
            }
            else
            {
                modelAchievement.Title = achievement.Title;
                modelAchievement.Description = achievement.Description;
                modelAchievement.Points = achievement.Points;
                _repository.Update(modelAchievement);
            }
        }
    }
}